package plugin

import (
	"fmt"
	"strings"
	"wf-deploy-agent/util"
)

type Javax struct {
	*BasePlugin
}

func (j *Javax) Start(jar string, options, environments []string) (string, error) {
	o, e := "", ""
	if options != nil && len(options) > 0 {
		for _, v := range options {
			o += fmt.Sprintf("%s,", strings.Trim(v, " "))
		}
	}

	if environments != nil && len(environments) > 0 {
		for _, v := range environments {
			e += fmt.Sprintf("%s,", strings.Trim(v, " "))
		}
	}

	util.Acquire(j.getFileName()).Lock()
	bytes, err := util.Exec(j.getFilePath(), "-f", jar, "-o", "\""+o+"\"", "-e", "\""+e+"\"", "start")
	util.Acquire(j.getFileName()).Unlock()
	return string(bytes), err
}

func (j *Javax) Stop(jar string, options, environments []string) (string, error) {
	o, e := "", ""
	if options != nil && len(options) > 0 {
		for _, v := range options {
			o += fmt.Sprintf("%s,", strings.Trim(v, " "))
		}
	}

	if environments != nil && len(environments) > 0 {
		for _, v := range environments {
			e += fmt.Sprintf("%s,", strings.Trim(v, " "))
		}
	}

	util.Acquire(j.getFileName()).Lock()
	bytes, err := util.Exec(j.getFilePath(), "-f", jar, "-o", "\""+o+"\"", "-e", "\""+e+"\"", "stop")
	util.Acquire(j.getFileName()).Unlock()
	return string(bytes), err
}

func (j *Javax) Restart(jar string, options, environments []string) (string, error) {
	o, e := "", ""
	if options != nil && len(options) > 0 {
		for _, v := range options {
			o += fmt.Sprintf("%s,", strings.Trim(v, " "))
		}
	}

	if environments != nil && len(environments) > 0 {
		for _, v := range environments {
			e += fmt.Sprintf("%s,", strings.Trim(v, " "))
		}
	}

	util.Acquire(j.getFileName()).Lock()
	bytes, err := util.Exec(j.getFilePath(), "-f", jar, "-o", "\""+o+"\"", "-e", "\""+e+"\"", "restart")
	util.Acquire(j.getFileName()).Unlock()
	return string(bytes), err
}
